package com.iams.manage.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.iams.common.utils.SecurityUtils;
import com.iams.elasticsearch.domain.ElasticsearchArchive;
import com.iams.elasticsearch.repository.ArchiveRepository;
import com.iams.elasticsearch.service.impl.DocumentContentExtractor;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.iams.common.utils.DateUtils;
import com.iams.manage.domain.BorrowRecord;
import com.iams.manage.domain.Document;
import com.iams.manage.service.IBorrowRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.iams.manage.mapper.ArchiveMapper;
import com.iams.manage.domain.Archive;
import com.iams.manage.service.IArchiveService;

/**
 * 档案列表Service业务层处理
 * 
 * @author zhjm
 * @date 2025-01-10
 */
@Service
public class ArchiveServiceImpl implements IArchiveService 
{
    @Autowired
    private ArchiveMapper archiveMapper;

    @Autowired
    private ArchiveRepository archiveRepository;

    @Autowired
    private DocumentContentExtractor documentContentExtractor;

    @Autowired
    private IBorrowRecordService borrowRecordService;

    /**
     * 查询档案列表
     * 
     * @param id 档案列表主键
     * @return 档案列表
     */
    @Override
    public Archive selectArchiveById(Long id)
    {
        return archiveMapper.selectArchiveById(id);
    }

    /**
     * 查询档案列表列表
     * 
     * @param archive 档案列表
     * @return 档案列表
     */
    @Override
    public List<Archive> selectArchiveList(Archive archive)
    {
        return archiveMapper.selectArchiveList(archive);
    }

    /**
     * 新增档案列表
     * 
     * @param archive 档案列表
     * @return 结果
     */
    @Override
    public int insertArchive(Archive archive)
    {
        archive.setCreateTime(DateUtils.getNowDate());

        String filePath = archive.getDianziLocation();


        ElasticsearchArchive document = new ElasticsearchArchive();

        document.setMysqlDanghao(archive.getDanghao());
        document.setTitle(archive.getName());

        document.setContent(getFileContent(filePath));

        document.setFileType(archive.getCarrierType());

        document.setDescription(archive.getDescription());

        document.setSecretLevel(archive.getSecretLevel());
        document.setCreateTime(archive.getCreateTime());
        document.setFilePath(filePath);

        archiveRepository.save(document);

        return archiveMapper.insertArchive(archive);
    }


    private String getFileContent(String filePath) {
        StringBuilder contentBuilder = new StringBuilder();
        File directory = new File(filePath);

        if (directory.exists() && directory.isDirectory()) {
            File[] files = directory.listFiles((dir, name) -> name.toLowerCase().endsWith(".docx"));
            if (files != null && files.length > 0) {
                for (File file : files) {
                    try {
                        contentBuilder.append(documentContentExtractor.extractContent(file, "docx"));
                    } catch (Exception e) {
                        System.err.println("Failed to extract content from: " + file.getName());
                        e.printStackTrace();
                    }
                }
            } else {
                System.out.println("No .docx files found in the directory.");
            }
        } else {
            System.err.println("The specified path is not a valid directory.");
        }

        return contentBuilder.toString();
    }

    /**
     * 修改档案列表
     * 
     * @param archive 档案列表
     * @return 结果
     */
    @Override
    public int updateArchive(Archive archive)
    {
        archive.setUpdateTime(DateUtils.getNowDate());
        return archiveMapper.updateArchive(archive);
    }

    /**
     * 批量删除档案列表
     * 
     * @param ids 需要删除的档案列表主键
     * @return 结果
     */
    @Override
    public int deleteArchiveByIds(Long[] ids)
    {
        return archiveMapper.deleteArchiveByIds(ids);
    }

    /**
     * 删除档案列表信息
     * 
     * @param id 档案列表主键
     * @return 结果
     */
    @Override
    public int deleteArchiveById(Long id)
    {
        return archiveMapper.deleteArchiveById(id);
    }

    /**
     * 修改档案列表
     *
     * @param document
     * @return 结果
     */
    @Override
    public int addDirectoryFiles(Document document)
    {
        return archiveMapper.addDirectoryFiles(document);
    }

    /**
     * 删除档案目录中的文件
     *
     * @param document
     * @return 结果
     */
    @Override
    public int deleteDirectoryFiles(Document document)
    {
        Archive archive = archiveMapper.selectArchiveById(document.getArchiveId());
        String directory = archive.getDirectory();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            List<Map<String, Object>> categories = objectMapper.readValue(directory, new TypeReference<List<Map<String, Object>>>() {});

            for (Map<String, Object> category : categories) {
                // 将 category.get("id") 转换为 Long 类型
                Long categoryId = Long.parseLong(category.get("id").toString());
                if (categoryId.equals(document.getDirectory())) {
                    List<?> filesList = (List<?>) category.get("files");
                    List<Long> files = filesList.stream()
                            .map(obj -> ((Number) obj).longValue())
                            .collect(Collectors.toList());
                    files.remove(document.getId());
                    category.put("files", files);
                }
                // 递归处理子类别
                List<Map<String, Object>> children = (List<Map<String, Object>>) category.get("children");
                if (children != null) {
                    processChildren(children, document);
                }
            }
            String updatedDirectory = objectMapper.writeValueAsString(categories);
            archive.setDirectory(updatedDirectory);
            return archiveMapper.deleteDirectoryFiles(archive);
        } catch (IOException e) {
            e.printStackTrace();
            return 0; // 或者抛出自定义异常
        }
    }

    private void processChildren(List<Map<String, Object>> children, Document document) {
        for (Map<String, Object> child : children) {
            // 将 child.get("id") 转换为 Long 类型
            Long childId = Long.parseLong(child.get("id").toString());
            if (childId.equals(document.getDirectory())) {
                List<?> filesList = (List<?>) child.get("files");
                List<Long> files = filesList.stream()
                        .map(obj -> ((Number) obj).longValue())
                        .collect(Collectors.toList());
                files.remove(document.getId());
                child.put("files", files);
            }
            // 递归处理子类别
            List<Map<String, Object>> subChildren = (List<Map<String, Object>>) child.get("children");
            if (subChildren != null) {
                processChildren(subChildren, document);
            }
        }
    }

    /**
     * 查询档案列表
     *
     * @param location 存放的档案柜的位置
     * @return 档案列表
     */
    @Override
    public List<Archive> getArchiveByLocation(String location) {
        if (location.endsWith("层")) {
            return archiveMapper.getArchiveByLocation(location);
        } else {
            return archiveMapper.getListByLocation(location);
        }
    }

    /**
     * 拖拽移动档案
     */
    @Override
    public int moveArchive(Long archiveId, String targetLocation) {
        Archive archive = archiveMapper.selectArchiveById(archiveId);
        if (archive == null) {
            throw new RuntimeException("档案不存在");
        }
        archive.setShitiLocation(targetLocation);
        return archiveMapper.updateArchive(archive);
    }

    /**
     * 档案全部下架
     */
    @Override
    public int takeOffArchives(List<Archive> archives) {
        for (Archive archive : archives) {
            archiveMapper.updateArchive(archive);
        }
        return archives.size();
    }

    /**
     * 获取未上架的档案列表
     */
    @Override
    public List<Archive> getUpArchiveList(Map<String, Object> query) {
        return archiveMapper.selectUpArchiveList(query);
    }

    /**
     * 检查用户是否具有查看档案的权限
     */
    @Override
    public boolean checkArchivePermission(Long archiveID)
    {
        // 使用：用户ID + 档案ID
        // 拿到对应的档案列表
        List<BorrowRecord> list = borrowRecordService.selectBorrowRecordByArchiveIDandUserID(archiveID, SecurityUtils.getLoginUser().getUserId());
        // 提前中断
        if(list.isEmpty())
        {
            return false;
        }
        for (BorrowRecord borrowRecord : list) {
            // 检查是否存在借阅记录且状态为已批准
            if (borrowRecord.getStatus().equals("approved")) {
                return true;
            }
        }
        return false;
    }
}
